package cn.edu.zzuli.wechat.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtils {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate template;

    /**
     * 写入数据，并设置过期时间
     */
    public boolean set(final String key, Object value, long time) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        try {
            template.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            log.info("存入redis成功，key：{}，value：{}", key, value);
            return true;
        } catch (Exception e) {
            log.error("存入redis失败，key：{}，value：{}", key, value);
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断是否有数据
     */
    public Boolean get(String key){
        Object res = template.opsForValue().get(key);
        if (res != null){
            return true;
        }else{
            return false;
        }
    }

}
